package android.fwirk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.fwirk.obj.CustomProgressDialog;
import android.fwirk.obj.StatusMessage;
import android.fwirk.obj.StatusMessageAdapter;
import android.fwirk.plurk.Plurk;
import android.fwirk.plurk.PlurkUser;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class PlurkActivity extends Activity implements OnItemLongClickListener {
	
	ListView timeLine;
	boolean gotPlurk;
	boolean hasPlurkNext;
	int tID=0;
	CustomProgressDialog progress;
	StatusMessageAdapter smAdapter;
	LinearLayout moreProgress;
	StatusMessage empty;
	StatusMessage more;
	
    Intent intent;
	private int DIALOG_PROGRESS=0;
	private int DIALOG_SIGNOUT=1;
	private AlertDialog signoutDialog;
	final static int MENU_RELOAD=0;
	final static int MENU_SIGNOUT=1;
	
	
    @Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.plurk);
    	timeLine=(ListView)findViewById(R.id.plurkTimeline);
        progress = new CustomProgressDialog(this);
        progress.setText("Retrieving timeline...");
		progress.setImage3(R.drawable.plurkd);
		progress.setImage1Visibility(View.GONE);
		progress.setImage2Visibility(View.GONE);
		progress.setImage3Visibility(View.VISIBLE);
		moreProgress=(LinearLayout) findViewById(R.id.moreBar);
		moreProgress.setVisibility(View.GONE);
		
		intent=new Intent(this,CustomDialogActivity.class);
		Builder bd=new Builder(this);
		signoutDialog = bd.setMessage("Sign out?").setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_POSITIVE) {
							showDialog(DIALOG_PROGRESS);
							new LogoutThread(logoutH, tID).start();
						}

					}
				}).setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_NEGATIVE) {
							dialog.dismiss();
						}

					}
				}).create();
        smAdapter=new StatusMessageAdapter(this, R.layout.row);
        timeLine.setAdapter(smAdapter);
        timeLine.setOnItemLongClickListener(this);
        empty=new StatusMessage();
        empty.setDrawID(R.drawable.alert);
        empty.setStatus("No recent plurks yet.");
        more=new StatusMessage();
        more.setDrawID(R.drawable.alert);
        more.setStatus("More");
        more.setMisc("Touch and hold to expand");
        smAdapter.clear();
        smAdapter.add(empty);
    	gotPlurk=false;
    	hasPlurkNext=false;
    	tID++;
    	showDialog(DIALOG_PROGRESS);
        GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_PLURK,true,false,tID%Integer.MAX_VALUE);
        pt.start();
        WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID);
        wt.start();
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode==Const.ACTIVITY_VIEW) {
    		if(resultCode==RESULT_OK) {
    			hasPlurkNext=false;
    			gotPlurk=false;
        		tID++;
        		progress.setText("Retrieving timeline..."); 
        		progress.setImage3(R.drawable.plurkd);
        		showDialog(DIALOG_PROGRESS);
        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_PLURK,true,false,tID%Integer.MAX_VALUE);
                pt.start();
        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
        		wt.start();
    		}
    	}
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	if(id==DIALOG_PROGRESS) {
    		return progress.getDialog();
    	}
    	else if(id==DIALOG_SIGNOUT) {
    		return signoutDialog;
    	}
    	return super.onCreateDialog(id);
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,MENU_RELOAD,0,"Reload Timeline")
			.setIcon(R.drawable.plurke);
		menu.add(0,MENU_SIGNOUT,0,"Sign out")
		.setIcon(R.drawable.fwirk);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case MENU_RELOAD:
				hasPlurkNext=false;
				gotPlurk=false;
        		tID++;
        		progress.setText("Retrieving timeline..."); 
        		progress.setImage3(R.drawable.plurkd);
        		showDialog(DIALOG_PROGRESS);
        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_PLURK,true,false,tID%Integer.MAX_VALUE);
                pt.start();
        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
        		wt.start();
				break;
			case MENU_SIGNOUT:
				showDialog(DIALOG_SIGNOUT);
				break;
		}
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK) {
			if(progress.isShowing()) {
				progress.dismiss();
			}
			else {
				showDialog(DIALOG_SIGNOUT);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
    
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		if(arg0==timeLine) {
			StatusMessage sm=((StatusMessage)(timeLine.getItemAtPosition(arg2)));
			if(!(sm.getDrawID()==R.drawable.alert)) {
				Const.curStatusMessage=sm;
				startActivityForResult(intent, Const.ACTIVITY_VIEW);
			}
			else {
				if(sm.getStatus().equals("More")) {
					moreProgress.setVisibility(View.VISIBLE);
					hasPlurkNext=false;
					gotPlurk=false;
	        		tID++;
	        		smAdapter.remove(sm);
	        		StatusMessage m=smAdapter.getItem(smAdapter.getCount()-1);
	        		Plurk p=(Plurk)m.getMsg();
	        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,p.getPosted(),Const.TYPE_PLURK,true,true,tID%Integer.MAX_VALUE);
	                pt.start();
	        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
	        		wt.start();
				}
			}
		}
		return false;
	}
	
	final Handler recentH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {	        	
	        	if(msg.getData().getBoolean("status") && msg.getData().getInt("type")==Const.TYPE_PLURK) {
	        		gotPlurk=true;
	        		progress.setImage3(R.drawable.plurke);
	        		if(msg.getData().getBoolean("hasNext")) {
	        			hasPlurkNext=true;
	        		}
	        	}
        	}
        }
    };
    
    final Handler waitRecentH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	StatusMessage sm;
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {
        		progress.hide();
	        	if(!gotPlurk) {
	        		Toast.makeText(getApplicationContext(), "Could not retrieve timeline", Toast.LENGTH_SHORT).show();
	        	}
	        	else {
	        		smAdapter.clear();
	        		if(gotPlurk) {
	        			Log.d("Test","recent plurks");
	        			for(Plurk p:Const.myPlurks) {
	        				PlurkUser user=p.getOwner();
	        				sm=new StatusMessage();
	        				sm.setMsg(p);
	        				sm.setDrawID(R.drawable.defaultplurkpic);
	        				String note="Anon: ";
	        				if(user!=null) {
		        				sm.setBitmap(user.getPicture());
		        				if(user.getDisplayName().length()>0) {
		        					note=user.getDisplayName()+": ";
			        			}
			        			else {
			        				note=user.getNickName()+": ";
			        			}
	        				}
		        			sm.setStatus(note+p.getContentRaw());
		        			sm.setMisc(DateFormat.format("hh:mm:ss aa - MMM dd, yyyy", p.getPosted())+"");
		        			if(p.getPlurkType()==Plurk.PLURK_TYPE_PRIVATE || p.getPlurkType()==Plurk.PLURK_TYPE_PRIVATE_RESPONDED) {
		        				sm.setMisc(sm.getMisc()+" - Private");
		        			}
		        			if(p.getPlurkType()==Plurk.PLURK_TYPE_PUBLIC || p.getPlurkType()==Plurk.PLURK_TYPE_PUBLIC_RESPONDED) {
		        				sm.setMisc(sm.getMisc()+" - Public");
		        			}
		        			smAdapter.add(sm);
	        			}
	        		}
	        		if(smAdapter.isEmpty()) {
	        			smAdapter.add(empty);
	        		}
	        		else if(hasPlurkNext) {
	        			smAdapter.add(more);
	        		}
	        		moreProgress.setVisibility(View.GONE);
	        		Toast.makeText(getApplicationContext(), "Retrieved timeline", Toast.LENGTH_SHORT).show();
	        	}
        	}
        }
    };
    
    final Handler logoutH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {	        	
	        	progress.hide();
        		finish();
        	}
        }
    };

}
